package com.christina.config;

import com.christina.engine.processing.RequestProcessor;
import com.christina.engine.processing.RequestProcessorChain;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;

import java.util.List;

/**
 * 处理器自动配置类
 * 负责自动发现和注册所有标记为@Component的处理器到责任链中
 * 
 * @author Christina
 */
@Configuration
@ConditionalOnBean(RequestProcessorChain.class)
public class ProcessorAutoConfiguration {
    
    private static final Logger logger = LoggerFactory.getLogger(ProcessorAutoConfiguration.class);
    
    private final RequestProcessorChain processorChain;
    private final List<RequestProcessor> allProcessors;
    
    @Autowired
    public ProcessorAutoConfiguration(RequestProcessorChain processorChain, 
                                      List<RequestProcessor> allProcessors) {
        this.processorChain = processorChain;
        this.allProcessors = allProcessors;
    }
    
    /**
     * 在应用上下文刷新完成后自动注册所有处理器
     */
    @EventListener(ContextRefreshedEvent.class)
    public void autoRegisterProcessors() {
        logger.info("Starting auto-registration of {} processors", allProcessors.size());
        
        int registeredCount = 0;
        for (RequestProcessor processor : allProcessors) {
            try {
                // 检查处理器是否已注册
                if (!processorChain.isProcessorRegistered(processor.getName())) {
                    processorChain.registerProcessor(processor);
                    registeredCount++;
                    logger.info("Auto-registered processor: {} (order: {})", 
                            processor.getName(), processor.getOrder());
                } else {
                    logger.debug("Processor already registered: {}", processor.getName());
                }
            } catch (Exception e) {
                logger.error("Failed to auto-register processor: {}", processor.getName(), e);
            }
        }
        
        logger.info("Auto-registration completed. Successfully registered {} processors", registeredCount);
        
        // 输出责任链信息
        logChainInfo();
    }
    
    /**
     * 记录责任链的详细信息
     */
    private void logChainInfo() {
        var chainInfo = processorChain.getChainInfo();
        logger.info("Processor chain status: total={}, enabled={}, built={}",
                chainInfo.getTotalProcessors(), 
                chainInfo.getEnabledProcessors(), 
                chainInfo.isChainBuilt());
        
        if (!chainInfo.getProcessors().isEmpty()) {
            logger.info("Processor chain order:");
            for (var processorInfo : chainInfo.getProcessors()) {
                logger.info("  {} -> {} (order: {}, enabled: {})", 
                        processorInfo.getName(), 
                        processorInfo.getClassName(),
                        processorInfo.getOrder(),
                        processorInfo.isEnabled());
            }
        }
    }
}